package com.starblink.store.detail.uinew

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.TimeUtils
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.log.SKLogger
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.rocketreserver.FetchMerchantWebByIdQuery
import com.starblink.rocketreserver.FetchMerchantWebFirstEnterInfoQuery
import com.starblink.rocketreserver.FetchMerchantWebOnSaleProductsRecommendQuery
import com.starblink.rocketreserver.FetchMerchantWebSelectForYouProductsRecommendQuery
import com.starblink.rocketreserver.FetchMerchantWebSuperDealsQuery
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.MerchantOnSaleRecommendProductQueryReq
import com.starblink.rocketreserver.type.MerchantRecommendSelectForYouProductQueryReq
import com.starblink.store.detail.bean.RvRecommendEmptyEntry
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class StoreDetailVM : BaseViewModel() {
    //===页面传参数据Start
    var storeId: String = ""
    //===页面传参数据End

    companion object {
        const val ERROR_GET_STORE_INFO_FAIL = 1 //获取店铺信息失败
        const val ERROR_STORE_INVALID = 2 //店铺失效
    }

    var curPageNoRecommend = 0 // 推荐商品列表当前页数，默认是0
    var storeInfoLD: MutableLiveData<MerchantWebVOF> = MutableLiveData() //店铺信息数据
    var storeFirstEnterInfoLD: MutableLiveData<FetchMerchantWebFirstEnterInfoQuery.FetchMerchantWebFirstEnterInfo?> =
        MutableLiveData() //店铺首次进入信息
    var pageRefreshDataLD: MutableLiveData<PageRefreshData> = MutableLiveData() //页面刷新数据
    var loadMoreRecommendProductLD: MutableLiveData<List<Any>?> =
        MutableLiveData() //加载更多推荐商品数据

    class PageRefreshData {
        var storeDeals: MerchantWebVOF? = null
        var saleProducts: List<ProductF>? = null
        lateinit var recommendProducts: List<Any>
        var storeFirstEnterInfo: FetchMerchantWebFirstEnterInfoQuery.FetchMerchantWebFirstEnterInfo? =
            null
    }

    /**
     * 加载页面数据（4个接口）
     */
    fun loadPageData() {
        //1.首先加载店铺信息
        //1.1如果加载失败或店铺无效显示错误页面
        //1.2如果店铺有效，并发加载剩余3种数据
        //1.2.1店铺内推荐信息接口获取异常 ，推荐模块显示Oops！No items found in this store.
        //1.2.2店铺deals接口获取异常，deals模块隐藏
        //1.2.3店铺Super Deals折扣好物接口获取异常，Super Deals折扣好物模块隐藏

        viewModelScope.launch {
            // 加载店铺信息
            SKLogger.e("dss", "11111")
            SkGqlClient.skQuery(
                FetchMerchantWebByIdQuery(
                    merchantWebNo = storeId
                )
            )?.data?.fetchMerchantWebById?.merchantWebVOF?.let {
                // 获取数据成功
                SKLogger.e("dss", "22222")
                if (it.valid == true) {
                    storeInfoLD.postValue(it)
                } else {
                    loadError(ERROR_STORE_INVALID)
                    return@launch
                }
            } ?: let {
                // 获取数据失败
                SKLogger.e("dss", "33333")
                loadError(ERROR_GET_STORE_INFO_FAIL)
                return@launch
            }

            // 并发加载首次进入信息
            async {
                SKLogger.e("dss", "44444")
                val storeFirstEnterInfo = fetchStoreFirstEnterInfo()
                storeFirstEnterInfoLD.postValue(storeFirstEnterInfo)
            }

            // 并发加载店铺Super Deal+折扣商品+推荐商品
            val storeDealsDeffer = async {
                SKLogger.e("dss", "5555")
                loadStoreDeals()
            }
            val saleProductsDeffer = async {
                SKLogger.e("dss", "6666")
                loadSaleProducts()
            }
            val recommendProductsDeffer = async {
                SKLogger.e("dss", "7777")
                loadRecommendProducts(true)
            }

            SKLogger.e("dss", "8888")
            // 处理推荐商品结果
            var recommendProducts = recommendProductsDeffer.await()
            // 如果接口异常或返回空列表，显示空视图
            if (recommendProducts == null) {
                recommendProducts = arrayListOf<Any>()
            }
            if (recommendProducts.isEmpty()) {
                recommendProducts.add(RvRecommendEmptyEntry())
            }

            // 返回结果
            val data = PageRefreshData().apply {
                this.storeDeals = storeDealsDeffer.await()
                this.saleProducts = saleProductsDeffer.await()
                this.recommendProducts = recommendProducts
            }
            SKLogger.e("dss", "9999")
            pageRefreshDataLD.postValue(data)
        }
    }

    /**
     * 加载店铺Super Deal信息
     */
    private suspend fun loadStoreDeals(): MerchantWebVOF? {
        return SkGqlClient.skQuery(
            FetchMerchantWebSuperDealsQuery(
                merchantWebNo = storeId
            )
        )?.data?.fetchMerchantWebSuperDeals?.merchantWebVOF
    }

    /**
     * 加载店铺折扣商品信息
     */
    private suspend fun loadSaleProducts(): List<ProductF>? {
        return SkGqlClient.skQuery(
            FetchMerchantWebOnSaleProductsRecommendQuery(
                req = MerchantOnSaleRecommendProductQueryReq(
                    merchantWebNo = storeId,
                    pageNo = 1,
                    pageSize = 6,
                    sortType = SortTypeEnum.DEFAULT.code,
                    scene = 1  // 1-折扣好物模块 2-view more
                )
            )
        )?.data?.fetchMerchantWebOnSaleProductsRecommend?.mapNotNull { it?.productF }
    }

    /**
     * 加载店铺推荐商品
     */
    private suspend fun loadRecommendProducts(refresh: Boolean): MutableList<Any>? {
        val requestPageNo = if (refresh) 1 else curPageNoRecommend + 1
        var products = SkGqlClient.skQuery(
            FetchMerchantWebSelectForYouProductsRecommendQuery(
                req = MerchantRecommendSelectForYouProductQueryReq(
                    merchantWebNo = storeId,
                    pageNo = requestPageNo,
                    pageSize = 20,
                )
            )
        )?.data?.fetchMerchantWebSelectForYouProductsRecommend?.mapNotNull { it?.productF }
        if (products == null) {
            return null
        }
        // 请求成功，页数+1
        curPageNoRecommend = requestPageNo
        val result = arrayListOf<Any>()
        products.forEach { result.add(it) }
        return result
    }

    /**
     * 加载店铺更多推荐商品
     */
    fun loadMoreRecommendProducts() {
        viewModelScope.launch {
            val products = loadRecommendProducts(false)
            loadMoreRecommendProductLD.postValue(products)
        }
    }

    /**
     * 获取店铺首次进入+订阅信息
     */
    private suspend fun fetchStoreFirstEnterInfo(): FetchMerchantWebFirstEnterInfoQuery.FetchMerchantWebFirstEnterInfo? {
        return SkGqlClient.skQuery(
            FetchMerchantWebFirstEnterInfoQuery()
        )?.data?.fetchMerchantWebFirstEnterInfo
    }
}